package p.ithorns.sample.spel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import javax.annotation.PostConstruct;

/**
 * TransactionApp
 *
 * @author HtL
 * @date 2024/5/30 11:02
 * @since 1.0.0
 */
@Slf4j
@SpringBootApplication
public class SpElApp  implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(SpElApp.class, args);
    }

    @Autowired
    ApplicationContext ctx;


    @PostConstruct
    public void init() {
        log.info("spElGetParam init ......");
    }

//    @Pointcut("@annotation(SpElGetParam)")
//    public void point() {
//    }


    @Override
    public void run(String... args) throws Exception {
        // https://blog.csdn.net/weixin_42645678/article/details/125414902
        // Spring Boot + Spel 表达式实现代码动态运行
        // 获取 Spring Bean 工厂
        ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory) ctx.getAutowireCapableBeanFactory();
        // 创建表达式解析器
        ExpressionParser expressionParser = new SpelExpressionParser();
        // 创建数据上下文
        StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
        evaluationContext.setBeanResolver(new BeanFactoryResolver(beanFactory));

        // 解析表达式
        String expression = "@testService.test('我是参数')";
        String result = expressionParser.parseExpression(expression).getValue(evaluationContext, String.class);

        log.info("动态调用结果: {}", result);
	}

}